const app = getApp();

Page({
  data: {
    balance: 0,           // 当前余额
    balanceText: '0.00',  // 格式化后的余额文本
    withdrawAmount: '',   // 提现金额
    minAmount: 1,         // 最小提现金额
    maxAmount: 0,         // 最大提现金额（等于余额）
    isLoading: false,     // 是否正在加载
    quickAmounts: [10, 50, 100, 200] // 快捷金额选项
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: '提现'
    });
    this.fetchWalletBalance();
  },

  // 获取钱包余额
  fetchWalletBalance() {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    if (!token || !riderId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    this.setData({ isLoading: true });

    wx.request({
      url: `${ip}/api/riders/info?id=${riderId}`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        if (res.data.code === 200) {
          const balance = parseFloat(res.data.data.money) || 0;
          this.setData({
            balance: balance,
            balanceText: balance.toFixed(2),
            maxAmount: balance,
            isLoading: false
          });
        } else {
          wx.showToast({
            title: '获取余额失败',
            icon: 'none'
          });
          this.setData({ isLoading: false });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        this.setData({ isLoading: false });
      }
    });
  },

  // 输入金额变化
  onAmountInput(e) {
    const value = e.detail.value;
    this.setData({
      withdrawAmount: value
    });
  },

  // 选择快捷金额
  onQuickAmountTap(e) {
    const amount = e.currentTarget.dataset.amount;
    this.setData({
      withdrawAmount: amount.toString()
    });
  },

  // 全部提现
  onWithdrawAll() {
    this.setData({
      withdrawAmount: this.data.balance.toString()
    });
  },

  // 提现
  onWithdraw() {
    const amount = parseFloat(this.data.withdrawAmount);
    const balance = this.data.balance;

    // 验证输入
    if (!this.data.withdrawAmount || isNaN(amount) || amount <= 0) {
      wx.showToast({
        title: '请输入有效金额',
        icon: 'none'
      });
      return;
    }

    if (amount < this.data.minAmount) {
      wx.showToast({
        title: `最小提现金额为${this.data.minAmount}元`,
        icon: 'none'
      });
      return;
    }

    if (amount > balance) {
      wx.showToast({
        title: '提现金额不能超过余额',
        icon: 'none'
      });
      return;
    }

    // 确认提现
    wx.showModal({
      title: '提现确认',
      content: `确认提现 ¥${amount.toFixed(2)} 到绑定银行卡？\n\n提现将在1-3个工作日内到账`,
      confirmText: '确认提现',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.processWithdraw(amount);
        }
      }
    });
  },

  // 处理提现请求
  processWithdraw(amount) {
    const ip = app.globalData.userIPInfo;
    const token = app.globalData.ridertoken;
    const riderId = app.globalData.riderId;

    wx.showLoading({ title: '提现中...' });

    // 使用支付宝小程序充值接口进行提现
    wx.request({
      url: `${ip}/api/alipay/miniProgramWithdraw`,
      method: 'POST',
      data: {
        userId: 23041091,
        amount: amount.toString(),
        opAppId: '' // 可选参数，如果需要指定特定的小程序AppId
      },
      header: {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        wx.hideLoading();

        if (res.data.code === 200) {
          wx.showToast({
            title: '提现申请已提交',
            icon: 'success'
          });

          // 提现成功后返回上一页并刷新
          setTimeout(() => {
            wx.navigateBack({
              success: () => {
                // 通知上一页刷新数据
                const pages = getCurrentPages();
                const prevPage = pages[pages.length - 2];
                if (prevPage && prevPage.fetchWalletInfo) {
                  prevPage.fetchWalletInfo();
                }
              }
            });
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '提现失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  }
});
